<template>
  <div v-if="state.tabsTitleArr.length" class="progress-box">
    <el-tabs class="tabs-border-box" @tab-change="handleChangeTab" v-model="state.tabActive">
      <el-tab-pane
        v-for="(item, index) in state.tabsTitleArr"
        :key="index"
        :label="`${item.modelName}-${item.disTypeName}`"
        :name="item.scid"
      >
        <div class="key-value">
          <div class="title">
            <span>当前计算进度</span>
          </div>
          <div class="title-key">
            <el-progress
              class="progress"
              color="#96F300"
              :text-inside="true"
              :stroke-width="20"
              :percentage="state.percentageData?.scProgress"
              status="success"
            />
          </div>
          <div class="title-time">
            <span>开始时间:</span>
            <i>{{ state.percentageData?.calcStart || '--' }}</i>
            <span>结束时间:</span>
            <i>{{ state.percentageData?.calcEnd || '--' }}</i>
          </div>
        </div>
        <div class="collapse-box">
          <el-collapse
            v-model="state.activeName"
            :key="index"
            v-for="(item, index) in state.percentageData?.zoneInfos"
          >
            <el-collapse-item :name="index + 1">
              <template #title>
                <div class="coll-title">
                  <div class="ip-img">
                    <img src="@/assets/images/dispatch/u38.png" />
                  </div>
                  <div class="ip-word">
                    <span>资源分区:</span>
                  </div>
                  <div class="ip-num">
                    <span>{{ item.zoneName }}</span>
                  </div>
                  <div class="ip-icon">
                    <i :class="iconActive(index + 1) ? 'downArrow2' : 'downArrow1'"></i>
                  </div>
                </div>
              </template>
              <div class="collapse-main">
                <div class="main-box">
                  <div
                    class="main-item"
                    :key="childIndx"
                    v-for="(childItem, childIndx) in item.groupInfos"
                  >
                    <div class="item-title">
                      <div class="title-icon">
                        <img src="@/assets/images/dispatch/u39.png" />
                      </div>
                      <div class="title-name">
                        <span>计算组：</span>
                      </div>
                      <div class="title-word">
                        <el-tooltip :content="childItem.groupName" placement="top">
                          <span>{{ childItem.groupName }}</span>
                        </el-tooltip>
                      </div>
                      <div class="title-ip">
                        <el-tooltip :content="childItem.host" placement="top">
                          <span>{{ childItem.host }}</span>
                        </el-tooltip>
                      </div>
                      <div class="progress-box">
                        <el-progress
                          class="progress"
                          color="#96F300"
                          :text-inside="true"
                          :stroke-width="20"
                          :percentage="childItem.progress"
                          status="success"
                        />
                      </div>
                    </div>
                    <div class="item-detail">
                      <div class="ul-box">
                        <div class="li-box" :key="num" v-for="(e, num) in childItem.secInfos">
                          <div class="li-item">
                            <div class="li-icon">
                              <img src="@/assets/images/dispatch/u40.png" />
                            </div>
                            <div class="li-name">
                              <span>
                                {{ `${e.blknm} 水文:${e.chlModel || '--'}` }}
                                {{ e.resvModel ? '水库:' + e.resvModel : '' }}
                              </span>
                            </div>
                          </div>
                          <div class="li-status">
                            <div class="status-icon">
                              <img src="@/assets/images/dispatch/u28.png" v-if="e.status == 0" />
                              <img src="@/assets/images/dispatch/u44.png" v-if="e.status == 4" />
                              <img
                                src="@/assets/images/dispatch/u54.png"
                                v-else-if="e.status == 1"
                              />
                              <img
                                src="@/assets/images/dispatch/u60.png"
                                v-else-if="e.status == 2"
                              />
                              <img
                                src="@/assets/images/dispatch/u62.png"
                                v-else-if="e.status == 3"
                              />
                              <img
                                src="@/assets/images/dispatch/waring.png"
                                v-else-if="e.status == 5"
                              />
                            </div>
                            <div class="status-name">
                              <span v-if="e.status == 0">未启动</span>
                              <span v-else-if="e.status == 1">等待中</span>
                              <span v-else-if="e.status == 2">水文计算中</span>
                              <span v-else-if="e.status == 3">水库调度中</span>
                              <span v-else-if="e.status == 4">已完成</span>
                              <span v-else-if="e.status == 5">异&nbsp;&nbsp;&nbsp;常</span>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
  <div v-else-if="state.createType" class="progress-box">
    <el-progress
      :percentage="100"
      status="success"
      :indeterminate="state.computStatus"
      :duration="5"
    />
    <div class="name">
      {{ state.computStatus ? '智能预报计算中' : '智能预报计算完成' }}
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, watch, defineExpose, onUnmounted } from 'vue'
import emitter from '@/utils/bus'
import {
  // 查询方案详情
  getDispatchSchemeDetail,
  getComputSchemeProgress,
  // 查询方案列表
  getDispatchSchemesList,
  getDispatchStatusValue,
  //获取四角值
  getDispatchManualSchemeProgSectionExtent
} from '@/services/modules/dispatch-manage.js'

import { ElMessage, ElMessageBox } from 'element-plus'
import { BASE_URL } from '@/services/config'
import { addImageToMap, removeLayer, clearLayer } from '@/utils/mapUtils'
import { debounce } from '@/utils/index'
import { IMG_LAYER } from '@/constants'
const state = reactive({
  //计算状态
  computStatus: false,
  createType: 0,
  timer: null,
  statusTimer: null,
  modelSchems: [],
  fourAngle: {},
  progressItem: '',
  tabActive: '',
  progressArr: [],

  activeName: ['1', '2'],
  //
  tabsTitleArr: [],
  // 当前子方案的计算进度信息
  percentageData: {},
  getProgressInterVal: '',
  getStatusInerVal: '',
  layerMapLoading: false
})
const props = defineProps({
  scId: {
    type: String,
    default: ''
  },
  zoneId: {
    type: String,
    // 默认大汶河流域
    default: ''
  },
  computStatus: {
    type: Boolean,
    default: false
  }
})
// 点击计算进度加载图层
function whetherLoadingMap(val) {
  if (val == 'second') {
    state.layerMapLoading = true
    acceptSchemeDetail(props.scId)
  } else {
    // 点击其它则不加载。去除图层
    state.layerMapLoading = false
    removeLayer(mapInstance, IMG_LAYER)
  }
}
//状态接口轮训
function getDispatchStatus(id) {
  // 根据是否打开计算进度 判断是否加载图层
  if (state.layerMapLoading) {
    clearLayer(window.mapInstance, 'import')

    addImageToMap(
      window.mapInstance,
      IMG_LAYER,
      BASE_URL + '/map/vectorTiles/getDispatchManualSchemeProgSection',
      state.fourAngle.xmin,
      state.fourAngle.ymin,
      state.fourAngle.xmax,
      state.fourAngle.ymax,
      id
    )
  }
}

const emit = defineEmits('refreshScheme')

//查看子方案四角值
function getFourAngle(id) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      getDispatchManualSchemeProgSectionExtent({ scid: id }).then((res) => {
        if (res.code === 200) {
          state.fourAngle = {
            xmax: res.data?.xmax,
            ymax: res.data?.ymax,
            xmin: res.data?.xmin,
            ymin: res.data?.ymin
          }
          resolve(state.fourAngle)
        }
      })
    }, 1000)
  })
}

const iconActive = (data) => {
  return state.activeName.includes(data)
}
// 循环获取当前子方案的计算进度。当为计算完成时 终止循环
function getByForEachChildProgress(id) {
  // 循环获取计算进度
  state.getProgressInterVal = setInterval(async () => {
    setTimeout(() => {
      acceptChildProgress(id)
      // 地图渲染
      getDispatchStatus(id)
      console.log(state.computeChildStatus, '终止循环1')
      // 如果计算完成
      if (state.percentageData.scProgress == '100.0') {
        console.log(state.computeChildStatus, '终止循环1')
        clearInterval(state.getProgressInterVal) // 终止循环
        state.getProgressInterVal = ''
        setTimeout(() => {
          emit('refreshScheme')
        }, 1000)
        // removeLayer(mapInstance, IMG_LAYER)
      }
    }, 0)
    emit('refreshScheme')
  }, 3000)
}
//获取计算状态
function getByForEachChildStatus(id) {
  state.getStatusInerVal = setInterval(() => {
    handleChildComputedStatus(id)

    if (state.computeChildStatus == 2) {
      console.log(state.computeChildStatus, '终止循环1')
      clearInterval(state.getStatusInerVal) // 终止循环
      state.getStatusInerVal = ''
      // emit('refreshScheme')
      // removeLayer(mapInstance, IMG_LAYER)
    }
    emit('refreshScheme')
  }, 3000)
}

// 查询选择的子方案的计算状态 id:子方案id
function handleChildComputedStatus(id) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      getDispatchStatusValue({
        scid: id,
        fcid: ''
      }).then((res) => {
        if (res.code === 200) {
          // 获取子方案计算状态
          state.computeChildStatus = res.data[0].status
          resolve(state.computeChildStatus)
        }
      })
    }, 0)
  })
}
// 查询选择的子方案的计算进度状态信
const handleChangeTab = debounce(async (val) => {
  clearInterval(state.getProgressInterVal)
  state.getProgressInterVal = ''
  clearInterval(state.getStatusInerVal)
  state.getStatusInerVal = ''
  console.log(val, '子方案')
  // 默认先去掉之前的计算图层
  removeLayer(mapInstance, IMG_LAYER)
  state.tabActive = val
  // 进度查询
  acceptChildProgress(val)
  //查询子方案计算状态
  handleChildComputedStatus(val)
  // 获取四角值
  await getFourAngle(val)

  // 地图渲染
  getDispatchStatus(val)
  // 如果子方案计算状态不为1：计算中，那么只查询一次进度,其它则循环查询进度
  if (state.computeChildStatus == 1) {
    // 获取当前子方案四角值
    // await getFourAngle(val)
    // 循环获取计算进度
    getByForEachChildProgress(val)
    //循环获取计算状态
    getByForEachChildStatus(val)
  } else {
    clearInterval(state.getProgressInterVal)
    state.getProgressInterVal = ''
    clearInterval(state.getStatusInerVal)
    state.getStatusInerVal = ''
  }
}, 1000)
// 查询子方案计算进度 :val:子方案id
function acceptChildProgress(val) {
  return new Promise((resolve, reject) => {
    getComputSchemeProgress({ scid: val }).then((res) => {
      if (res.code === 200) {
        state.percentageData = res.data
        resolve(state.percentageData)
      }
    })
  })
}
// 1.查询方案详情
watch(
  () => {
    props.scId
  },
  () => {
    console.log(props.scId, '方案进度id')
    if (props.scId) acceptSchemeDetail(props.scId)
  },
  {
    deep: true,
    immediate: true
  }
)
watch(
  () => {
    props.computStatus
  },
  () => {
    if (props.computStatus == 1) {
      state.computStatus = true
    } else if (props.computStatus == 2) {
      state.computStatus = false
    }
    console.log('123', state.computStatus)
  },
  {
    deep: true,
    immediate: true
  }
)
// 根据父方案 查询子方案
function acceptSchemeDetail(id, computStatus) {
  state.computStatus = computStatus
  state.createType = 0
  console.log(id, '详情')
  clearInterval(state.getProgressInterVal)
  state.getProgressInterVal = ''
  clearInterval(state.getStatusInerVal)
  state.getStatusInerVal = ''
  state.tabsTitleArr = []
  // state.progressArr = []
  // scBelong:（0：洪水预报，1：调度预报）
  getDispatchSchemeDetail({ scid: id, scBelong: 0 }).then(async (res) => {
    if (res.code == 200) {
      // 获取子方案列表
      state.tabsTitleArr = res.data.models.info
      if (state.tabsTitleArr.length) {
        // 默认选中第一个子方案tab
        handleChangeTab(state.tabsTitleArr[0].scid)
      }
      if (res.data.bases.createTypeName === '智能水文') {
        state.createType = 1
      }
    }
  })
}
//删除方案后 如果删除的方案id == 正在调用的父方案id
// function deleteScheme(deleteId) {

//   clearInterval(state.getProgressInterVal)

// }
defineExpose({ acceptSchemeDetail, whetherLoadingMap })
onUnmounted(() => {
  clearInterval(state.getProgressInterVal)
  state.getProgressInterVal = ''
  clearInterval(state.getStatusInerVal)
  state.getStatusInerVal = ''
})
</script>

<style lang="less" scoped>
.progress-box {
  margin-top: 10px;
  height: 100%;
  :deep(.tabs-border-box) {
    height: 95%;
    :deep(.el-tabs__header) {
      margin: 0;
      .el-tabs__item {
        padding: 0 30px;
        font-size: 20px;
        font-weight: 500;
      }
    }
  }
}

.key-value {
  display: flex;
  line-height: 35px;
  font-size: 14px;
  margin-top: 10px;
  padding: 0 15px;
  .title {
    margin-right: 25px;
    span {
      color: #797979;
    }
  }
  .title-key {
    :deep(.el-progress-bar__outer) {
      border: 1px solid #96f300;
    }
    .progress {
      width: 250px;
    }
    display: flex;
    justify-content: center;
    align-items: center;
    span {
      color: #0154db;
    }
  }
  .title-time {
    margin-left: 80px;
    color: #797979;

    display: flex;
    align-items: center;
    i {
      color: black;
      margin-left: 15px;
    }
    span {
      margin-left: 30px;
    }
  }
}
.collapse-box {
  margin-top: 10px;
  padding: 0px 15px;
  overflow-y: auto;
  height: 80%;
  .el-collapse {
    .el-collapse-item {
      // height: 30px;
      // :deep(.el-collapse-item__header) {
      //   // height: 30px;
      // }
      :deep(.el-collapse-item__arrow) {
        display: none;
      }
      // :deep(.el-collapse-item__header) {
      //   justify-content: space-between;
      // }
      .coll-title {
        display: flex;
        position: relative;
        width: 100%;
        .ip-img {
          display: flex;
          justify-content: center;
          align-items: center;
          margin-right: 5px;
          img {
            width: 20px;
            height: 20px;
          }
        }
        .ip-word {
          margin-right: 5px;
          span {
            color: #797979;
          }
        }
        .ip-num {
          margin-right: 200px;
          span {
            color: black;
            font-weight: 600;
          }
        }
        .ip-status {
          span {
            color: #81be3a;
          }
        }
        .ip-icon {
          display: flex;
          justify-content: center;
          align-items: center;
          position: absolute;
          right: 10px;
          top: 15px;
          cursor: pointer;
          .downArrow1 {
            display: inline-block;
            width: 20px;
            height: 20px;
            background-image: url(@/assets/images/dispatch/u61.png);
            background-repeat: no-repeat;
            background-size: 100% 100%;
          }
          .downArrow2 {
            display: inline-block;
            width: 20px;
            height: 20px;
            transform: rotate(-180deg);
            background-image: url(@/assets/images/dispatch/u61.png);
            background-repeat: no-repeat;
            background-size: 100% 100%;
          }
        }
      }
      .collapse-main {
        height: 100%;
        .main-box {
          .main-item {
            margin-top: 5px;
            .item-title {
              display: flex;
              .title-icon {
                margin-right: 2px;
                margin-left: 20px;
                img {
                  width: 20px;
                  height: 20px;
                }
              }
              .title-name {
                margin-right: 15px;
                span {
                  color: #797979;
                  font-size: 12px;
                }
              }
              .progress-box {
                width: 150px;
                margin-left: 50px;
              }
              .title-word {
                width: 120px;
                span {
                  display: inline-block;
                  width: 120px;
                  overflow: hidden;
                  white-space: nowrap;
                  text-overflow: ellipsis;
                  color: #0054db;
                  font-size: 12px;
                  cursor: pointer;
                }
              }
              .title-ip {
                width: 120px;
                span {
                  display: inline-block;
                  width: 120px;
                  color: black;
                  font-size: 12px;
                  overflow: hidden;
                  white-space: nowrap;
                  text-overflow: ellipsis;
                  cursor: pointer;
                }
              }
            }
            .item-detail {
              height: 100%;
              .ul-box {
                max-height: 200px;
                overflow-y: auto;
                .li-box {
                  display: flex;
                  justify-content: space-between;
                  margin: 15px 0 0 50px;
                  .li-item {
                    display: flex;
                    font-size: 12px;
                    .li-icon {
                      margin-right: 5px;
                      img {
                        width: 20px;
                        height: 20px;
                      }
                    }
                    .li-name {
                      span {
                        color: black;
                      }
                    }
                  }
                  .li-status {
                    display: flex;
                    margin-right: 100px;
                    .status-icon {
                      margin-right: 5px;
                      img {
                        width: 20px;
                        height: 20px;
                      }
                    }
                    .status-name {
                      span {
                        color: black;
                        font-size: 12px;
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
</style>
